package com.ruix.app.ui.user;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.hyphenate.EMCallBack;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ActionMapper;
import com.ruix.app.mapper.ApiMapper;
import com.ruix.app.mapper.SystemConfigMapper;
import com.ruix.app.model.SystemConfig;
import com.ruix.app.model.User;
import com.ruix.app.model.WXAccessToken;
import com.ruix.app.model.WXUserInfo;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.app.SplashActivity;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.main.MainActivity;
import com.ruix.app.util.EMMessageUtil;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.MD5Util;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/10.
 */

public class LoginActivity extends BaseActivity {

    private static int REQUEST_BIND= 212;
    private String wechat_ruix_login_state = "wechat_ruix_login_state";//
    private String wechat_scope = "snsapi_userinfo";//"snsapi_userinfo"; snsapi_base

    private  Button loginBtn;


    @Override
    protected int loadViewLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
       loginBtn = (Button) findViewById(R.id.btn_weichat_login);
//        deleteOauth();
    }

    @Override
    protected void initLocalData() {
        UMShareAPI.get(this).deleteOauth(this, SHARE_MEDIA.WEIXIN, null);
    }

    @Override
    protected void initListener() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isInstallWeiXin()){
                    showLoading();
                    loginBtn.setEnabled(false);
                    loginWithWiXin();
//                    getPlatInfo();
                } else {
                    showErrorTip("请安装微信");
                }
            }
        });
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    // 设置状态栏颜色
    protected int statusBarTintColor() {
        return R.color.white;
    }


    private void resetView(){
        loginBtn.setEnabled(true);
        dismissLoading();
    }

    private void wechatLogin(final String accessToken, final String openid) {
        RequestFactory.login(accessToken, openid, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                if (value != null) {
                    JSONObject data = value.optJSONObject("data");
                    if (data != null) {
                        boolean binded = data.optInt("bind_mobie", 0) == 1;
                        if (binded) {
                            getWXUserinfo(accessToken,openid);
                        } else {
                            JSONObject userObject = data.optJSONObject("user");
                            User user = new User().parse(userObject);
                            if (!user.isImportInfo()){
                                Intent intent = ImportUserInfoActivity.newIntent(LoginActivity.this, "SplashActivity", null);
                                startActivity(intent);
                            } else {
                                UserManager.sharedInstance().updateUserInfo(user);
                                UserManager.sharedInstance().loginEMClient();
                                loadMain();
                            }
                        }
                    }
                }

            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
                resetView();
            }

            @Override
            public void onComplete() {
                resetView();
            }
        });
    }

    private void bindPhone(WXUserInfo value) {
        Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
        intent.putExtra("wxuserinfo",value);
        startActivityForResult(intent,REQUEST_BIND);
    }

    private void getWXUserinfo(String accessToken,String openid){
        showLoading();
        RequestFactory.getWXUserinfo(accessToken, openid, new ApiMapper<WXUserInfo>() {
            @Override
            public WXUserInfo transform(JSONObject response) {
                WXUserInfo wxUserInfo = null;
                if (response != null){
                    wxUserInfo = new WXUserInfo().parse(response);
                }
                return wxUserInfo;
            }
        }, new RXObserver<WXUserInfo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(WXUserInfo value) {
                bindPhone(value);
            }

            @Override
            public void onError(Throwable e) {
                bindPhone(null);
            }

            @Override
            public void onComplete() {
                dismissLoading();

            }
        });

    }





    private void loadMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_BIND && resultCode == RESULT_OK){
            loadMain();
            finish();
        }
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }



    private boolean isInstallWeiXin(){
       return UMShareAPI.get(this).isInstall(this,SHARE_MEDIA.WEIXIN);
    }


    private void loginWithWiXin(){
        UMShareAPI.get(this).doOauthVerify(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map != null && map.get("access_token") != null && map.get("openid") != null){
                    String code = map.get("access_token");
                    String openid = map.get("openid");
                    wechatLogin(code,openid);
                } else {
                    resetView();
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                resetView();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                resetView();

            }
        });
    }

    public void getPlatInfo(){
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
            }
        });

    }


    private void deleteOauth(){
        UMShareAPI.get(this).deleteOauth(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

}
